﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>deferred</title>
    <style>
        #results {
            border: solid 2px gray;
            height: 200px;
        }
    </style>
</head>
<body>
    <div id="results">
    </div>
</body>
</html>
<script src="Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
    //bad!
    /*
    $.get("http://services.odata.org/V4/Northwind/Northwind.svc/Products?$select=ProductName");
    $('#results').text('done'); //this is an outright lie!
    */
    /*
    //good
    //using the service by asyc using promise pattern
    $.get("http://services.odata.org/V4/Northwind/Northwind.svc/Products?$select=ProductName")
        .then(function(data) {
            $('#results').text('done with the service call'); //this is truly happening AFTER the return
        })
        .fail(function(err) {
            //happens when I fail
        })
        .always(function(alw) {
        console.log("always");
    });*/
    //done should be last handler...then then then and done

    $('#results').append('starting the async call');

    myDeferredAsync()
      .then(function () {
          $('#results').append('</br>done with the custom deferred function');
      });

    function myDeferredAsync() {
        var d = $.Deferred();
        setTimeout(function () { d.resolve(); }, 5000);
        return d.promise();
    }
</script>
